import { t } from 'i18next'
import createVanilla from 'zustand/vanilla'
import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import Alert from '@/components/Alert'
import { VipListModel } from '@/api/manager/vip/interface'
import { Mt, MtEntity } from '@/api/manager/mt'
import { transVipList } from '@/api/manager/vip/translator'
import { fetchSaveVipList, fetchVipList } from '@/api/manager/vip'
import { useMccStore } from '../../store'
import { differenceBy } from 'lodash-es'
import { dealDrop, listToggle } from '@/utils/listSlice'

type StateStore = { list: VipListModel; showList: VipListModel; _start: string | null; _changes: string[] }

type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	fetchInit: () => Promise<void>
	itemHandle: (mtKey: string, type: 'click' | 'ctrl' | 'shift') => void
	removeMt: (mtKey: string) => void
	removeAllChecked: () => void
	clear: () => void
	save: () => Promise<void>
	add: (list: MtEntity[]) => void
	drop: (p: { mts: VipListModel; dropIndex: number; from?: string }) => void
	ws: {
		mcc_meeting_viplist: (list: MtEntity[]) => void
		mcc_mt: (list: MtEntity[]) => void
	}
}
const initialState: StateStore = {
	list: [],
	showList: [],
	_start: null,
	_changes: [],
}
export const store = createVanilla<IStore>()(
	subscribeWithSelector((set, get, api) => ({
		...initialState,
		update: (d) => set({ ...d }),
		fetchInit: async () => {
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			let res = await fetchVipList(meetingMoid)
			if (res) {
				set({ list: res, showList: res })
			} else {
				Alert(t('获取VIP配置列表失败'))
			}
		},
		reset: () => {
			//vip 不能重置，作为全局缓存参与排序
			// get().resetToggle()
			// set(initialState)
		},
		itemHandle: (mtKey, type) => {
			const { showList, _start, _changes } = get()
			const result = listToggle(
				showList,
				{
					_start,
					_changes,
					action: type,
				},
				mtKey
			)
			set({ showList: result.list, _start: result._start, _changes: result._changes })
		},
		removeMt: (mtKey) => {
			const _list = get().showList.filter((l) => l.mtKey !== mtKey)
			set({ showList: _list })
		},
		removeAllChecked: () => {
			const list = get().showList
			const unCheckedList = list.filter((l) => !l.status.checked)
			if (unCheckedList.length === list.length) {
				Alert(t('请选择人员'))
			} else {
				set({ showList: unCheckedList })
			}
		},
		clear: () => {
			set({ showList: [] })
		},
		save: async () => {
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			const list = get().showList
			let res = await fetchSaveVipList(
				meetingMoid,
				list.map((x) => x.mcc)
			)
			if (!res) {
				Alert(t('设置VIP失败'))
			}
		},
		add: (addList) => {
			let _updates = addList.filter((mt) => mt.conf_level === 2)
			const list = get().showList
			let mts = transVipList(_updates)
			const insertList = differenceBy(mts, list, (x) => x.mtKey)
			if (insertList.length + list.length > 20) {
				Alert(t('VIP终端数量不得超过20个'))
				return
			}
			set({ showList: [...list, ...insertList] })
		},
		drop: ({ mts: _updates, from, dropIndex }) => {
			const list = get().showList
			const result = dealDrop(list, { mts: _updates, dropIndex, isOther: from !== 'vip' })
			if (result.length > 20) {
				Alert(t('VIP终端数量不得超过20个'))
				return
			}
			set({ showList: result })
		},
		ws: {
			mcc_meeting_viplist: (list) => {
				let _list = transVipList(list)
				set({ list: _list, showList: _list })
			},
			mcc_mt: (mts) => {
				const prevList = get().showList
				let vipList = mts.filter((x) => !!x.vip)
				if (vipList.length === 0) return
				let flag = false
				for (const prev of prevList) {
					let vip = vipList.find((x) => x.mt_key === prev.mtKey)
					if (vip) {
						if (!!vip.online !== prev.mcc.status.isOnline) {
							prev.mcc.status.isOnline = !!vip.online
							flag = true
						}
					}
				}
				if (flag) {
					set({ showList: [...prevList] })
				}
			},
		},
	}))
)
export const useVipStore = create(store)
